import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */


typeMapping = [
  (~/(?i)int/)                      : "int",
  (~/(?i)float|double|decimal|real/): "double",
  (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
  (~/(?i)date/)                     : "java.sql.Date",
  (~/(?i)time/)                     : "java.sql.Time",
  (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  def indexes = calcIndexes(table)
  def packageName = getPackageName(dir)
  new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table, indexes, packageName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, className, fields, table, indexes, packageName) {
    out.println "package $packageName"
    out.println ""
    out.println "import com.api.dao.entities.BasicEntities;"
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println "import com.baomidou.mybatisplus.annotation.TableField;"
    out.println "import com.fasterxml.jackson.annotation.JsonProperty;"
    out.println "import lombok.Data;"
    out.println "import lombok.EqualsAndHashCode;"
    out.println "import lombok.ToString;"
    out.println ""
    out.println ""
    out.println "/**\n" +
            " * ${table.getComment()} 实体类 \n" +
            " * \n" +
            " * @author 李大牛家的牛 (scafel@163.com)\n" +
            " * @className ${className}\n" +
            " * @createDate ${new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) }\n" +
            " * @description ${table.getComment()}实体类 \n" +
            " */\n"
    out.println "@TableName(value = \"${table.getName()}\")\n" +
            "@Data\n" +
            "@EqualsAndHashCode(callSuper = true)\n" +
            "@ToString(callSuper = true)"
    out.println "public class $className extends BasicEntities{"
    out.println ""
    def excludeFields = [ "id", "code", "sort", "status", "protect",  "hot", "deleted",  "version", "c_time", "u_time", "d_time",  "c_a_u_id", "u_a_u_id", "u_m_u_id", "c_m_u_id", "u_os", "u_ip",
    ]
    fields.each() {
        if (excludeFields.contains(it.fildName)) {
            return
        }

        out.println "\t/**\n" +
                "\t* ${it.commoent}\n" +
                "\t* <p>默认值： ${it.defaultValue}</p>\n" +
                "\t*/"
        if (it.annos != "") out.println "\t${it.annos}"
        out.println "\t@TableField(value = \"${it.fildName}\")"
        out.println "\t@JsonProperty(value = \"${it.fildName}\")"
        out.println "\tprivate ${it.type} ${it.name};"
    }

    out.println ""
    out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDasType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 fildName: col.getName(),
                 name : javaName(col.getName(), false),
                 defaultValue : col.getDefault(),
                 type : typeStr,
                 commoent: col.getComment(),
                 annos: ""
               ]]
  }
}

def calcIndexes(table) {
    DasUtil.getTableKeys(table)
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
    .collect { Case.LOWER.apply(it).capitalize() }
    .join("")
    .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def dbName(str) {
    def parts = str.split("_");
    parts[0]
}
